<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 样板旁站记录编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 项目信息 -->
        <base-info ref="baseInfo" :form="form" :editModel="editModel" :isNoBorder="editModel=='0'" @companychange="companychange" />
        <!-- 样板工程旁站信息 -->
        <a-card :bordered="false" style="margin-bottom: 80px">
          <title-name title="样板工程旁站信息"></title-name>
          <custom-form
            :formList="formList"
            @getOption="(name, e) => (option = e)"
            :form="form"
            :editModel="editModel == 0 ? 'V' : ''"
            :formComponents="$refs"
            @change="handleChangeTwo"
          >
            <template #name>
              <div v-if="editModel == 0" style="margin-top: -3px">{{ form.name }}</div>
              <a-row v-else type="flex" align="middle">
                <div :style="{ width: editModel == 0 ? '100%' : 'calc(100% - 108px)' }">
                  <BaseInput v-model="form.name"></BaseInput>
                </div>
                <ChooseModel v-if="editModel != 0" :form="form" />
              </a-row>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div
        class="btn_box page-btn-right-top"
      >
        <!-- 打印 -->
        <BasePrintButton
          v-if="editModel == 0"
          :beforePrintFn="() => getPritContent('CSCEC8XN-EQ-B30603')"
          class="button_right"
        />
        <a-button
          :disabled="loading[0] || loading[1]"
          v-if="editModel == 1 && statusCode === '0'"
          type="danger"
          class="button_right"
          @click="handleRemove"
          >删除草稿</a-button
        >
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && statusCode === '0') || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >保存草稿</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button type="primary" @click="$multiTab.close()">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { stationRecord, projectImplementationPlan } from '@/api/quality/sample' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 班主
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import ChooseModel from '../components/ChooseModel' // 选择样板信息

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BaseInfo,
    BasePrintButton,
    ChooseModel
  },
  data() {
    return {
      loading: { 0: false, 1: false },
      editModel: 0,
      id: '',
      form: {
        viewName: ""
      },
      statusCode: '', // 审批状态
      selectedRowKeys: [], // 样板信息选中id集合
      selectedRow: [], // 样板信息选中对象集合
      dataSource: [], // 样板信息列表
      searchArr: [
        // 搜索框
        {
          name: '样板名称',
          type: 'input',
          value: 'name'
        },
        {
          name: '样板部位',
          type: 'input',
          value: 'part'
        },
        {
          name: '计划制作时间',
          type: 'dateRange',
          value: 'makeDate',
          attr: {
            rangeFormat: ['beginDate', 'endDate']
          }
        }
      ],
      columns: [
        {
          title: '样板名称',
          dataIndex: 'name',
          ellipsis: true
        },
        {
          title: '样板部位',
          dataIndex: 'part',
          ellipsis: true
        },

        {
          title: '计划制作时间',
          dataIndex: 'makeDate',
          ellipsis: true
        },
        {
          title: '劳务单位',
          dataIndex: 'subcontractor',
          ellipsis: true
        },
        {
          title: '实施要点',
          dataIndex: 'implPoints',
          ellipsis: true
        }
      ], // 试验计划表头
      option: {
        subContractorOrgId: ''
      }, // 分包商选中项
      requestLoading: false, // 关联样板名称loading
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        name: [{ required: true, message: '请输入或选择样板名称', trigger: 'blur' }],
        part: [{ required: true, whitespace: true, message: '请输入样板部位', trigger: 'blur' }],
        subcontractorId: [{ required: true, message: '请选择样板施工单位', trigger: 'change' }],
        constructionDate: [{ required: true, message: '请选择施工日期', trigger: 'change' }],
        recordDate: [{ type: 'array', required: true, message: '请选择旁站时间', trigger: 'change' }],
        bystanderIds: [{ required: true, message: '请选择旁站人', trigger: 'change' }],
        laborForceNum: [{ required: true, whitespace: true, message: '请输入劳动力数量、工时', trigger: 'change' }],
        mechanics: [{ required: true, whitespace: true, message: '请输入机械、台班', trigger: 'change' }],
        materialScience: [{ required: true, whitespace: true, message: '请输入材料名称、规格型号', trigger: 'change' }],
        controlLink: [{ required: true, whitespace: true, message: '请输入关键控制环节', trigger: 'change' }],
        acceptanceCriteria: [{ required: true, whitespace: true, message: '请输入验收标准', trigger: 'change' }],
        fileArrays: [{ required: true, type: 'array', message: '请上传图片', trigger: 'change' }],
        makeProcess: [{ required: true, whitespace: true, message: '请输入样板制作过程', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['查看样板旁站记录', '编辑样板旁站记录', '添加样板旁站记录'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      stationRecord
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          // 格式化旁站时间
          if (res.data?.recordDate && this.editModel != 0) {
            res.data.recordDate = [res.data.startDate, res.data.endDate]
          }
          this.form = res.data
          this.form.viewName = this.form.branchCompanyName + "/" + this.form.projectName
          this.statusCode = res.data.statusCode
        })
        .catch((res) => {
          this.loading[0] = false
        })
    }
  },
  computed: {
    subContractorOrgId() {
      return this.option?.subContractorOrgId ?? ''
    },
    formList() {
      return [
        {
          keyName: 'name',
          slot: true,
          label: '样板名称'
        },
        {
          keyName: 'part',
          type: 'a-input',
          label: '样板部位'
        },
        {
          keyName: 'subcontractorId',
          viewName: 'subcontractor',
          type: SelectSubcontractor,
          label: '样板施工单位',
          attrs: {
            form: this.form,
            extraSubcontractor: {
              subContractorId: '-1',
              name: '分包单位未进场'
            },
            showSearch: true,
            isClear: this.editModel == 2
          }
        },
        {
          keyName: 'recordDate',
          type: 'a-range-picker',
          placeholder: ['请选择日期', '请选择日期'],
          label: '旁站时间',
          span: 8,
          attrs: {
            valueFormat: 'YYYY-MM-DD HH:mm',
            format: 'YYYY-MM-DD HH:mm',
            showTime: { format: 'HH:mm' }
          }
        },
        {
          keyName: 'constructionDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '施工日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'bystanderIds',
          viewName: 'bystander',
          type: SelectPersonByProject,
          label: '旁站人员',
          attrs: {
            mode: 'multiple',
            maxTagCount: 2,
            id: this.form.branchCompanyId,
            projectId: this.form.projectId,
            statusCode: '0',
            showSearch: true
          }
        },
        {
          keyName: 'laborForceNum',
          type: 'a-input',
          label: '劳动力数量、工时'
        },
        {
          keyName: 'mechanics',
          type: 'a-input',
          label: '机械、台班'
        },
        {
          keyName: 'materialScience',
          type: 'a-input',
          label: '材料名称、规格型号'
        },
        {
          keyName: 'controlLink',
          type: 'a-input',
          label: '关键控制环节'
        },
        {
          keyName: 'acceptanceCriteria',
          type: 'a-input',
          label: '验收标准'
        },
        {
          keyName: 'makeProcess',
          type: 'BaseTextarea',
          label: '样板制作过程',
          span: 24
          // attrs: {
          //   type: 'textarea',
          // },
        },
        {
          keyName: 'other',
          type: 'BaseTextarea',
          label: '其他',
          span: 24
        },
        {
          keyName: 'fileArrays',
          type: 'uploadFile',
          businessCode: 'QM02',
          attrs: {
            disabled: this.editModel == '0',
            editModel: this.editModel,
            uploadType: 'image'
          },
          label: '图片上传',
          span: 24
        }
      ]
    }
  },
  methods: {
    /**
     * @description: 样板信息复选项改变
     * @param {*} selectedRowKeys：选中项
     */
    onSelectChange(selectedRowKeys, selectedRow) {
      // console.log(selectedRowKeys, selectedRow)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    /**
     * @description: 关联样板信息后回调
     */
    handleConfirm() {
      this.$set(this.form, 'name', this.selectedRow?.[0]?.name)
      this.$set(this.form, 'part', this.selectedRow?.[0]?.part)
      this.$set(this.form, 'subcontractor', this.selectedRow?.[0]?.subcontractor)
      this.$set(this.form, 'subcontractorId', this.selectedRow?.[0]?.subcontractorId)
      // 重置搜索表单
      this.$refs.searchData?.form.resetFields()
      this.visible = false
    },
    /**
     * @description: 打开选择试验项目弹窗
     */
    handleOpen(e = {}) {
      this.requestLoading = true
      projectImplementationPlan
        .downPost({
          ...e,
          mark: 1, // mark：0 样板记录；1 样板旁站
          projectId: this.form.projectId
        })
        .then((res) => {
          this.requestLoading = false
          this.dataSource = res.data || []
          if (res.code === 200 && res.data?.length) {
            if (this.experimentTable?.details?.length) {
              this.selectedRowKeys = this.experimentTable.details.map((i) => i.id)
            }
            if (!this.visible) {
              this.visible = true
            }
          } else {
            this.$message.warning('没有样板信息可以选择！')
          }
        })
        .catch(() => {
          this.requestLoading = false
        })
    },
    companychange(branchCompanyId) {
      this.form.branchCompanyId = branchCompanyId
      this.handleChange()
    },
    /**
     * 项目改变时
     */
    handleChange() {
      let form = this.form
      if (form.subcontractorId) {
        form.subcontractorId = ''
      } else {
        this.$set(this.form, 'subcontractorId', '')
      }
      if (form.bystanderIds) {
        form.bystanderIds = []
      } else {
        this.$set(this.form, 'bystanderIds', [])
      }
    },
    /**
     * 劳务单位改变时
     */
    handleChangeTwo(name) {
      if (name === 'subcontractorId') {
        let form = this.form
        if (form.bystanderIds) {
          form.bystanderIds = []
        } else {
          this.$set(this.form, 'bystanderIds', [])
        }
      }
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return stationRecord.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      let name = ['updatePost', 'add'][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          statusCode === 0 && that.$refs.ruleForm.clearValidate()
          // 提交表单
          that.loading[statusCode] = true
          let form = that.$clone(that.form)
          if (form.recordDate?.length) {
            form.startDate = form.recordDate[0]
            form.endDate = form.recordDate[1]
            delete form.recordDate
          }
          form.statusCode = statusCode
          stationRecord[name](form)
            .then((res) => {
              that.loading[statusCode] = false
              if (res.code === 200 || res.data.code === 200) {
                that.$message.success(['保存', '提交'][statusCode] + '成功！')
                that.$multiTab.close()
              }
            })
            .catch((res) => {
              // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
              that.loading[statusCode] = false
            })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>
